package io.gitee.bowen_lee.netty.netty;

import java.net.InetSocketAddress;

import io.gitee.bowen_lee.netty.bowen.server.BowenAcceptChannelHandle;
import io.gitee.bowen_lee.netty.bowen.server.BowenBridgeClientChannelHandle;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * netty 服务端写法
 * 
 * @author Bowen
 * @since 2022-01-14 11:30:43
 */
public class ServerMain {
  public static void main(String[] args) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    ServerBootstrap bs = new ServerBootstrap();
    ChannelFuture bind = bs.group(group, group)
        .channel(NioServerSocketChannel.class)
        // 私人的
        .childHandler(new BowenBridgeClientChannelHandle())
        .bind(new InetSocketAddress("127.0.0.1", 9090)).sync();
    System.out.println("服务端启动!");
    bind.sync().channel().closeFuture().sync();
    System.out.println("服务端关闭!");
  }

  /**
   * 使用自定义的桥
   * 
   * @return
   */
  public ChannelHandler getMyServerBootstrap() {
    return new BowenBridgeClientChannelHandle();
  }

  /**
   * 使用 原生桥
   * 
   * @return
   */
  public ChannelInitializer<NioSocketChannel> getServerBootstrap() {
    return new ChannelInitializer<NioSocketChannel>() {

      @Override
      protected void initChannel(NioSocketChannel ch) throws Exception {
        ChannelPipeline channelPipeline = ch.pipeline();
        channelPipeline.addLast(new BowenAcceptChannelHandle() {

          @Override
          public void println(ChannelHandlerContext ctx, String msgStr) {
            if ("hello world".equals(msgStr)) {
              System.out.println("回复 received!");
              ctx.writeAndFlush(Unpooled.copiedBuffer("received!".getBytes()));
            }
          }
        });
      }

    };

  }

}
